<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="基础信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <px-form-item label="保养计划编码" prop="code">
                  <px-input v-model="formValue.code" disabled placeholder="自动生成" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="保养计划名称" prop="name">
                  <px-input v-model="formValue.name" placeholder="请输入保养计划名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="地块" prop="facCode">
                  <px-select v-model="formValue.facCode" placeholder="请选择地块" clearable filterable @change="selectEqpData = []">
                    <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="保养开始时间" prop="startDate">
                  <px-date-picker
                    v-model="formValue.startDate"
                    value-format="YYYY-MM-DD"
                    type="date"
                    :disabled-date="disabledDate"
                    placeholder="请选择保养开始时间"
                    @change="formValue.planEndTime = ''"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="保养负责人" prop="userId">
                  <px-select-v2 v-model="formValue.userId" filterable clearable :options="approvalList" placeholder="请选择保养负责人" />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="设备信息">
          <template v-slot:content>
            <div style="display: flex">
              <px-button style="margin-left: 6px" type="primary" :disabled="!formValue.facCode" plain @click="eqpVisible = true">选择设备</px-button>
              <px-button style="margin-right: 16px" plain type="danger" @click="handleBatchDeleteEqp">批量删除</px-button>
            </div>
            <px-table
              :data="selectEqpData"
              style="margin-top: 20px"
              class="equip-table"
              size="small"
              max-height="340px"
              border
              @selection-change="selectionChange"
            >
              <px-table-column type="selection" min-width="40" align="center" />
              <px-table-column type="index" label="序号" min-width="56" />
              <px-table-column prop="typeName" label="设备类型" min-width="234" show-overflow-tooltip />
              <px-table-column prop="eqpId" label="设备编号" min-width="234" show-overflow-tooltip />
              <px-table-column prop="eqpName" label="设备名称" min-width="234" show-overflow-tooltip />
              <px-table-column prop="facName" label="地块" min-width="234" show-overflow-tooltip />
              <px-table-column prop="positionNameAll" label="安装位置" min-width="234" show-overflow-tooltip />
              <px-table-column prop="specification" label="规格型号" min-width="234" show-overflow-tooltip />
              <px-table-column fixed="right" label="操作" min-width="64" align="center">
                <template #default="scope">
                  <px-tooltip content="删除" placement="top">
                    <px-button link type="danger" icon="Delete" @click="handleDeleteEqp(scope.$index)" />
                  </px-tooltip>
                </template>
              </px-table-column>
            </px-table>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="保养项目">
          <template v-slot:content>
            <div style="display: flex">
              <px-button style="margin-left: 6px" type="primary" plain @click="itemsVisible = true">选择保养项目</px-button>
              <px-button style="margin-right: 16px" plain type="danger" @click="handleBatchDeleteItems">批量删除</px-button>
            </div>
            <px-table
              :data="selectItemsData"
              style="margin-top: 20px"
              class="equip-table"
              size="small"
              max-height="340px"
              border
              @selection-change="selectionItemsChange"
            >
              <px-table-column type="selection" min-width="40" align="center" />
              <px-table-column type="index" label="序号" min-width="56" />
              <px-table-column prop="name" label="保养项目名称" min-width="240" show-overflow-tooltip />
              <px-table-column prop="standard" label="保养标准" min-width="666" show-overflow-tooltip>
                <template #default="scope">
                  <span v-for="(item, index) in scope.row.attachmentList" :key="item.id">
                    {{ item.originalName }}{{ scope.row.attachmentList?.length > 1 && index !== scope.row.attachmentList?.length - 1 ? "，" : "" }}
                  </span>
                </template>
              </px-table-column>
              <px-table-column prop="confirmWayName" label="确认方式" min-width="150" show-overflow-tooltip />
              <px-table-column prop="createByName" label="创建人" min-width="150" show-overflow-tooltip />
              <px-table-column prop="createTime" label="创建时间" min-width="200" show-overflow-tooltip />
              <px-table-column fixed="right" label="操作" min-width="64" align="center">
                <template #default="scope">
                  <px-tooltip content="删除" placement="top">
                    <px-button link type="danger" icon="Delete" @click="handleDeleteItems(scope.$index)" />
                  </px-tooltip>
                </template>
              </px-table-column>
            </px-table>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">提交</px-button>
    </div>
    <EqpList :typeCode="typeCode" :facCode="formValue.facCode" :visible="eqpVisible" @closeDialog="closeDialog" />
    <ItemsList :typeCode="typeCode" :visible="itemsVisible" @closeDialog="closeItemsDialog" />
  </div>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { addPlan, createPlanCode, queryPlanEqp, queryPlanItems, updatePlan } from "@/api/erc/epm";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import dayjs from "dayjs";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import EqpList from "./EqpList.vue";
import ItemsList from "./ItemsList.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "typeCode", "planData"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {},
  eqpVisible: false,
  itemsVisible: false,
  approvalList: [],
  selectEqpData: [],
  selectItemsData: [],
  selectIds: [], // 设备批量删除用到的ids
  selectItemIds: [], // 设备批量删除用到的ids
  facCodeList: []
});
const { formValue, eqpVisible, itemsVisible, approvalList, selectEqpData, selectItemsData, selectIds, selectItemIds, facCodeList } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  code: [{ required: true, message: "保养计划编码不能为空", trigger: "blur" }],
  name: [{ required: true, message: "保养计划名称不能为空", trigger: "blur" }],
  facCode: [{ required: true, message: "保养计划名称不能为空", trigger: "blur" }],
  startDate: [{ required: true, message: "请选择保养开始时间", trigger: "blur" }],
  userId: [{ required: true, message: "保养负责人不能为空", trigger: "blur" }]
}));

// 获取后端自动生成的工单号
const getToolCode = async () => {
  const data = await createPlanCode();
  formValue.value.code = data;
};

const disabledDate = (time: any) => {
  return time.getTime() < Date.now() - 86400000; // 禁用今天之前的日期
};

const handleGetApprovalList = async () => {
  approvalList.value = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
};

// 表格多选框选中-保养设备
function selectionChange(val: any) {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
}

// 表格多选框选中-保养项目
function selectionItemsChange(val: any) {
  selectItemIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectItemIds.value.push(item.id);
    }
  });
}

// 关闭选择设备的弹窗并且拿到选择的数据
const closeDialog = (val?: any) => {
  eqpVisible.value = false;
  if (val) {
    selectEqpData.value = selectEqpData.value?.concat(val)?.filter((obj, index, self) => {
      return self.map(x => x.id).indexOf(obj.id) === index;
    });
  }
};

const handleDeleteEqp = index => {
  selectEqpData.value.splice(index, 1);
};

const handleDeleteItems = index => {
  selectItemsData.value.splice(index, 1);
};

const handleBatchDeleteEqp = () => {
  selectEqpData.value = selectEqpData.value.filter(item => selectIds.value.indexOf(item.id) === -1);
};

const handleBatchDeleteItems = () => {
  selectItemsData.value = selectItemsData.value.filter(item => selectItemIds.value.indexOf(item.id) === -1);
};

// 关闭选择保养项目弹窗并且拿到选择的数据
const closeItemsDialog = (val?: any) => {
  itemsVisible.value = false;
  if (val) {
    selectItemsData.value = selectItemsData.value?.concat(val)?.filter((obj, index, self) => {
      return self.map(x => x.id).indexOf(obj.id) === index;
    });
  }
};

// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value.resetFields();
    formValue.value = {};
    selectEqpData.value = [];
    selectItemsData.value = [];
    handleGetApprovalList();
    facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
    if (props.drawerType === "add") {
      getToolCode();
      formValue.value.startDate = dayjs(Date.now());
    } else if (props.drawerType === "edit") {
      formValue.value = JSON.parse(JSON.stringify(props.planData));
      getEqpItems();
    }
  } else {
    formValue.value = {};
  }
});

// 获取详情接口
const getEqpItems = async () => {
  selectEqpData.value = await queryPlanEqp({ code: props.planData.code });
  selectItemsData.value = await queryPlanItems({ code: props.planData.code });
};

// 返回主页面
const backMainPage = () => {
  PxMessageBox.confirm(`确认退出工单吗？退出后内容将不会保存，请谨慎操作`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      formRef.value.resetFields();
      emits("backMainPage");
    })
    .catch(() => {});
};

// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const eqpIdList = selectEqpData.value.map(item => item.eqpId);
      const projectIdList = selectItemsData.value.map(item => item.id);
      if (eqpIdList.length === 0) {
        PxMessage.warning("请至少选择一个设备");
        return;
      }
      if (projectIdList.length === 0) {
        PxMessage.warning("请至少选择一个保养项目");
        return;
      }
      if (props.drawerType === "add") {
        await addPlan({ typeCode: props.typeCode, ...formValue.value, eqpIdList, projectIdList });
        PxMessage.success("创建成功");
        emits("backMainPage");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        await updatePlan({ typeCode: props.typeCode, id: props.planData.id, ...formValue.value, eqpIdList, projectIdList });
        PxMessage.success("编辑成功");
        emits("backMainPage");
        emits("queryTable");
      }
    }
  });
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
